package com.geeksaga.common.util;

import java.util.GregorianCalendar;
import java.util.concurrent.atomic.AtomicReference;

import com.geeksaga.enums.DateTimeFormatList;

/**
 * @author newbie
 * @since 0.1
 */
public class KeyGenerator {
    private static final AtomicReference<String> BEFORE_GEN_KEY = new AtomicReference<String>();
	private static final String SUFFIX_BBS = "99";

	private KeyGenerator() {}
	
    /**
     * @return
     */
    public static String generatorKey() {
        return generatorKey("");
    }
    
    /**
     * @return
     */
    public static String generatorBbsKey() {
    	return generatorKey(SUFFIX_BBS);
    }
    
    /**
     * @param suffix
     * @return
     */
    public static String generatorKey(String suffix) {
        StringBuilder generateKey = new StringBuilder();
        generateKey.append(calculateDate());

        boolean isValidationKey = false;
        if(BEFORE_GEN_KEY.get() != null && !"".equals(BEFORE_GEN_KEY.get())) {
            if(Long.valueOf(generateKey.toString()) > Long.valueOf(BEFORE_GEN_KEY.get()))
                isValidationKey = true;
        } else {
            isValidationKey = true;
        }
        
        BEFORE_GEN_KEY.set(generateKey.toString());
        if(isValidationKey)
            return generateKey.append(suffix).toString();
        
        return generatorKey(suffix);
    }
    
    /**
     * @return
     */
    private static String calculateDate() {
    	long yyyy = Integer.parseInt(DateConvertor.getDateFormat(DateTimeFormatList.YYYY));
    	
    	StringBuilder sb = new StringBuilder();
    	sb.append(yyyy).append((GregorianCalendar.getInstance().get(GregorianCalendar.DAY_OF_YEAR) + 100));
    	sb.append(DateConvertor.getDateFormat(DateTimeFormatList.HHMMSSSSS));
    	
    	return sb.toString();
    }
}